<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="visible"
    width="1000px"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    @close="closeDialog"
  >
    <div class="card_area">
      <div>
        <el-image
          style="width: 120px; height: 150px"
          fit="cover"
          :src="formData.headPic ? formData.headPic : avatar"
          alt="身份证头像"
        />
      </div>
      <div>
        <el-button
          v-if="dialogAddOrEdit.detail !== '编辑'"
          type="primary"
          :loading="resolveLoading"
          @click="resolveCard"
          >读身份证
        </el-button>
      </div>
    </div>
    <el-form ref="addOrEditFormRef" v-loading="loading" :model="formData" :rules="rules" label-width="185" size="">
      <div style="display: flex; align-items: center">
        <el-image :src="divider" style="width: 25px; margin-right: 20px"></el-image>
        <span style="font-size: 15px; font-weight: bold; color: #29d">身份证信息</span>
      </div>
      <el-row justify="start" class="d_left">
        <el-col :span="9" class="">
          <el-form-item label="身份证号" prop="cardNumber">
            <el-input v-model="formData.cardNumber" placeholder="请输入身份证号" :disabled="true" readonly />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" :disabled="true" readonly />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender" placeholder="请选择性别" clearable readonly :disabled="true">
              <el-option v-for="item in gender" :key="item.value" :value="item.value" :label="item.label"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="formData.birthday"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择出生日期"
              readonly
              :disabled="true"
            />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="发证机关" prop="cardOrg">
            <el-input v-model="formData.cardOrg" placeholder="请输入发证机关" :disabled="true" readonly />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="民族" prop="nation">
            <el-input v-model="formData.nation" placeholder="请输入民族" :disabled="true" readonly />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="证件有效期" prop="cardStartdate">
            <el-date-picker
              v-model="formData.cardStartdate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择证件有效期"
              :disabled="true"
              readonly
            />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="至" prop="cardEnddate">
            <el-date-picker
              v-model="formData.cardEnddate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择证件有效期"
              :disabled="true"
              readonly
            />
          </el-form-item>
        </el-col>

        <el-col :span="20" class="">
          <el-form-item label="家庭住址" prop="address">
            <el-input
              v-model="formData.address"
              style="width: 98%"
              placeholder="请输入家庭住址"
              :disabled="true"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="display: flex; align-items: center">
        <el-image :src="divider" style="width: 25px; margin-right: 20px"></el-image>
        <span style="font-size: 15px; font-weight: bold; color: #29d">基本信息</span>
      </div>

      <el-row justify="start" class="d_left">
        <el-col :span="9" class="">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="婚姻状况" prop="maritalStatus">
            <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状况" clearable>
              <el-option
                v-for="item in maritalStatus"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="紧急联系人" prop="urgentLinkman">
            <el-input v-model="formData.urgentLinkman" placeholder="请输入紧急联系人" />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="紧急联系电话" prop="urgentLinkmanHone">
            <el-input v-model="formData.urgentLinkmanHone" placeholder="请输入紧急联系电话" />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="特长" prop="specialty">
            <el-input v-model="formData.specialty" placeholder="请输入特长" />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="文化程度" prop="cultureLevel">
            <el-select v-model="formData.cultureLevel" placeholder="请选择文化程度" clearable>
              <el-option
                v-for="item in cultureLevel"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="政治面貌" prop="politicsType">
            <el-select v-model="formData.politicsType" placeholder="请选择政治面貌" clearable>
              <el-option
                v-for="item in politicsType"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="加入公会时间" prop="joinedTime">
            <el-date-picker
              v-model="formData.joinedTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择加入公会时间"
            />
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="是否购买工伤或意外伤害保险" prop="hasBuyInsurance">
            <el-select v-model="formData.hasBuyInsurance" placeholder="请选择是否购买保险" clearable>
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="9" class="">
          <el-form-item label="是否有重大病史" prop="hasBadMedicalHistory">
            <el-select v-model="formData.hasBadMedicalHistory" placeholder="请选择是否有重大病史" clearable>
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }} </el-button>
        <el-button @click="closeDialog()">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <modelPromise v-if="dialogModel.visible" :dialog-model="dialogModel" @sendModelClose="sendModelClose"></modelPromise>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from "vue";
import { addCorpPerson, editCorpPerson, getCorpPersonInfo } from "@/api/corp/person/index.ts";
import { CorpPersonForm } from "@/api/corp/person/types";
import avatar from "@/assets/page/avatar.jpg";
import { getDicts } from "@/store/modules/dict";
import { useToDeviceSocket } from "@/utils/socket";
import modelPromise from "@/views/corp/person/common/modelPromise.vue";
import moment from "moment";
import divider from "@/assets/page/bankuai_new.png";

import { useScreen } from "@/store/modules/screen";

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);

function initScreen() {}

const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增人员信息",
      footBtn: "新增",
      id: 0,
    }),
  },
});

const dialogModel = reactive({
  visible: false,
  detail: "corp",
});

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const resolveLoading = ref(false);
let visible = ref(props.dialogAddOrEdit.visible);
const formData = reactive<CorpPersonForm>({});
const addOrEditFormRef = ref(ElForm);

const rules = reactive<FormRules<CorpPersonForm>>({
  projectCorpId: [{ required: true, message: "请选择参建企业", trigger: "blur" }],
  cardNumber: [
    { required: true, message: "身份证号码不能为空", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
      trigger: "blur",
    },
  ],
  mobile: [
    { required: true, message: "手机号码不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "性别不能为空", trigger: "blur" }],
  name: [{ required: true, message: "人员姓名不能为空", trigger: "blur" }],
  birthday: [{ required: true, message: "出生日期不能为空", trigger: "blur" }],
  cardOrg: [{ required: true, message: "发证机关不能为空", trigger: "blur" }],
  cardStartdate: [{ required: true, message: "证件有效期不能为空", trigger: "blur" }],
  cardEnddate: [{ required: true, message: "证件有效期不能为空", trigger: "blur" }],
  nation: [{ required: true, message: "民族不能为空", trigger: "blur" }],
});

onMounted(async () => {
  initScreen();

  let tempFormData;
  if (props.dialogAddOrEdit.id) {
    loading.value = true;
    tempFormData = await getCorpPersonInfo(props.dialogAddOrEdit.id);
    tempFormData = tempFormData.data;
    Object.assign(formData, tempFormData);
    loading.value = false;
    tempFormData = null;
  }
});

/* 读取身份证 */
function resolveCard() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.headPic = "";
  resolveLoading.value = true;
  let { connet, onOpen, onMessage, token, socket } = useToDeviceSocket((error: any) => {
    if (!error) {
      resolveLoading.value = false;
      console.log("读卡失败!", error);
      return;
    }
    if (error.type == "error") {
      resolveLoading.value = false;
      ElMessage.error("读卡失败!请检查设备连接!");
    }
    if (error.type == "close") {
      if (error.code == 1006) {
        ElMessageBox({
          title: "程序下载",
          showCancelButton: true,
          showConfirmButton: false,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          message: () =>
            h(
              "div",
              {
                style: {},
              },
              [
                h(
                  "span",
                  {
                    style: {
                      color: "red",
                    },
                  },
                  `未检测到身份证阅读器守护程序，请打开程序或点击下面链接重新下载。`
                ),
                h("br", undefined, undefined),
                h(
                  "span",
                  {
                    style: {
                      color: "red",
                    },
                  },
                  "程序下载地址"
                ),
                h(
                  "a",
                  {
                    href: "/app/download/SmzTestCardReader_Setup.exe",
                    target: "_blank",
                    download: "CardReaderSetup.exe",
                    style: {
                      color: "blue",
                      textDecoration: "underline",
                    },
                  },
                  "点击下载"
                ),
                h("br", undefined, undefined),
                h(
                  "span",
                  {
                    style: {
                      color: "red",
                    },
                  },
                  "有关读卡器守护程序使用教程请"
                ),
                h(
                  "a",
                  {
                    href: "/app/tutorial.html",
                    target: "_blank",
                    style: {
                      color: "blue",
                      textDecoration: "underline",
                    },
                  },
                  "点击查看"
                ),
              ]
            ),
        });
      }
    }
    resolveLoading.value = false;
    console.log("读卡失败!", error);
  });
  connet("");
  onOpen(null);
  onMessage(getCardInfo);
  // setTimeout(() => {
  // 	if(socket && socket.readyState !== 1){
  // 		resolveLoading.value = false;
  // 		ElMessage.error("读卡失败!请检查设备连接!")
  // 	}
  // }, 5000)
}

const cardInfo = ref();

async function getCardInfo(e) {
  let result = JSON.parse(e.data);
  let { success, msg, data } = result;
  if (!success) {
    if (msg == "版本不一致") {
      // if (msg) {
      let box = await ElMessageBox({
        title: "程序下载",
        showCancelButton: true,
        showConfirmButton: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        message: () =>
          h(
            "div",
            {
              style: {},
            },
            [
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                `当前身份证阅读器守护程序版本已过期，请关闭现有程序并点击下面链接重新下载。`
              ),
              h("br", null, null),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "程序下载地址"
              ),
              h(
                "a",
                {
                  href: "/app/cardreader-setup-20230907.exe",
                  target: "_blank",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击下载"
              ),
              h("br", null, null),
              h(
                "span",
                {
                  style: {
                    color: "red",
                  },
                },
                "有关读卡器守护程序使用教程请"
              ),
              h(
                "a",
                {
                  href: "/app/tutorial.html",
                  target: "_blank",
                  style: {
                    color: "blue",
                    textDecoration: "underline",
                  },
                },
                "点击查看"
              ),
            ]
          ),
      })
        .then((val) => true)
        .catch((val) => false);
    } else if (msg == "身份证读卡器信息未登记") {
      dialogModel.visible = true;
    } else {
      ElMessage.error(msg);
    }
    resolveLoading.value = false;
    return;
  }

  cardInfo.value = data;
  formData.token = data.token;
  formData.address = data.address;
  formData.cardStartdate = moment(data.beginDate).format("YYYY-MM-DD");
  formData.birthday = moment(data.birth).format("YYYY-MM-DD");
  formData.cardOrg = data.company;
  formData.cardEnddate = moment(data.endDate).format("YYYY-MM-DD");
  formData.cardNumber = data.id;
  formData.name = data.name;
  formData.nation = ChineseEthnicityFilter(Number(data.race));
  formData.gender = data.sex === "1" ? "男" : "女";
  formData.headPic = "data:image/png;base64," + data.headPic;
  resolveLoading.value = false;
}

function ChineseEthnicityFilter(val) {
  let temp = ChineseEthnicity.filter((item) => item.value === val);
  if (temp && temp[0]) {
    return temp[0].label;
  } else {
    return "";
  }
}

/* 发送当前弹窗关闭 */
function sendClose(query) {
  emit("sendClose", query);
}

function sendModelClose(query) {
  dialogModel.visible = false;
}

/**
 * 关闭弹窗
 */
function closeDialog(query) {
  let { handleClose } = useToDeviceSocket();
  handleClose();
  visible.value = false;
  sendClose(query);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();

  formData.personId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  let tempData = Object.assign({}, formData);
  tempData.headPic = "";
  tempData.name = "";
  tempData.cardNumber = "";
  tempData.cardOrg = "";
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      resolveLoading.value = true;
      const id = formData.personId;
      if (id) {
        editCorpPerson(id, tempData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        addCorpPerson(tempData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => {
            loading.value = false;
            resolveLoading.value = false;
          });
      }
    }
  });
}

const gender = getDicts("gender"); //性别
const politicsType = getDicts("politicsType"); //政治面貌
const cultureLevel = getDicts("cultureLevel"); //文化程度
const maritalStatus = getDicts("maritalStatus"); //婚姻状况
const ChineseEthnicity = getDicts("chineseEthnicity"); //民族状况
</script>

<style lang="scss" scoped>
.d_left {
  margin-left: 100px;
}

.card_area {
  position: absolute;
  left: 60px;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin-top: 28px;
}

:deep(.el-form-item) {
  flex-wrap: wrap;
}

.dialog_footer {
  // display: flex;
  // justify-content: center;
}

:deep(.el-input) {
  width: 200px;
}

:deep(.el-input__inner) {
  // width: 200px;
}

:deep(.el-input__wrapper) {
  width: 200px;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
</style>
